package org.breathe.dynamic.thread.pool.core.handler;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.breathe.dynamic.thread.pool.core.monitor.collector.MetricsCollector;
import org.breathe.thread.pool.common.entity.ThreadPoolStats;

import java.util.List;
import java.util.ServiceLoader;

/**
 * 收集数据处理器
 * @author: breathe
 * @createTime: 2025-04-14
 */
@Slf4j
public class CollectorHandler {
    private static final List<MetricsCollector> COLLECTORS = Lists.newArrayList();

    private CollectorHandler() {
        //支持spi机制
        ServiceLoader.load(MetricsCollector.class).forEach(COLLECTORS::add);
        log.info("COLLECTORS: {}", COLLECTORS);
    }

    public void collect(ThreadPoolStats poolStats, String type) {
        if (poolStats == null) {
            return;
        }
        for (MetricsCollector collector : COLLECTORS) {
            if (collector.support(type)) {
                collector.collect(poolStats);
                break;
            }
        }
    }

    public static CollectorHandler getInstance() {
        return CollectorHandlerHolder.INSTANCE;
    }

    private static class CollectorHandlerHolder {
        private static final CollectorHandler INSTANCE = new CollectorHandler();
    }
}
